package org.jeecg.modules.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysEmployee;
import org.jeecg.modules.system.service.ISysEmployeeService;
import org.jeecg.modules.wms.entity.WmsPurchaseOrder;
import org.jeecg.modules.wms.entity.WmsPurchaseOrderDetail;
import org.jeecg.modules.wms.service.*;
import org.jeecg.modules.wms.vo.WmsPurchaseOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.wms.entity.WmsPurchaseArrivalInspection;
import org.jeecg.modules.wms.entity.WmsPurchaseReturnExchange;

import java.math.BigDecimal;

import org.jeecg.modules.wms.vo.WmsPurchaseOrderDetailVO;

/**
 * @Description: 采购单管理
 * @Author: jeecg-boot
 * @Date: 2023-07-17
 * @Version: V1.0
 */
@Api(tags = "采购单管理")
@RestController
@RequestMapping("/wms/purchase")
@Slf4j
public class WmsPurchaseOrderController extends JeecgController<WmsPurchaseOrder, IWmsPurchaseOrderService> {
    @Autowired
    private IWmsPurchaseOrderService wmsPurchaseOrderService;

    @Autowired
    private IWmsPurchaseOrderDetailService wmsPurchaseOrderDetailService;

    @Autowired
    private ISysEmployeeService employeeService;

    @Autowired
    private IWmsPurchaseArrivalInspectionService wmsPurchaseArrivalInspectionService;

    @Autowired
    private IWmsPurchaseReturnExchangeService wmsPurchaseReturnExchangeService;

    /**
     * 分页列表查询
     *
     * @param wmsPurchaseOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "采购单-分页列表查询")
    @ApiOperation(value = "采购单-分页列表查询", notes = "采购单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmsPurchaseOrder>> queryPageList(WmsPurchaseOrder wmsPurchaseOrder,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        // 创建查询条件
        QueryWrapper<WmsPurchaseOrder> queryWrapper = new QueryWrapper<>();

        // 手动处理查询条件
        Map<String, String[]> parameterMap = req.getParameterMap();

        // 采购单号查询
        String purchaseNo = req.getParameter("purchaseNo");
        if (purchaseNo != null && !purchaseNo.isEmpty()) {
            queryWrapper.like("purchase_no", purchaseNo);
        }

        // 供应商查询
        String supplier = req.getParameter("supplier");
        if (supplier != null && !supplier.isEmpty()) {
            queryWrapper.like("supplier", supplier);
        }

        // 状态查询
        String status = req.getParameter("status");
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }

        // 是否自动生成查询
        String isAutoGenerated = req.getParameter("isAutoGenerated");
        if (isAutoGenerated != null && !isAutoGenerated.isEmpty()) {
            queryWrapper.eq("is_auto_generated", isAutoGenerated);
        }

        // 审核人查询
        String approveName = wmsPurchaseOrder.getApproveName();
        List<Object> usernameList = employeeService.listObjs(new QueryWrapper<SysEmployee>().select("username").like("emp_name", approveName));
        if (usernameList != null && !usernameList.isEmpty()) {
            queryWrapper.in("approve_by", usernameList);
        }

        // 审核时间查询
        String approveTimeStart = req.getParameter("approveTimeStart");
        String approveTimeEnd = req.getParameter("approveTimeEnd");

        if (approveTimeStart != null && !approveTimeStart.isEmpty()) {
            queryWrapper.ge("approve_time", approveTimeStart + " 00:00:00");
        }

        if (approveTimeEnd != null && !approveTimeEnd.isEmpty()) {
            queryWrapper.le("approve_time", approveTimeEnd + " 23:59:59");
        }

        // 物料编码和物料名称查询
        String materialCode = req.getParameter("materialCode");
        String materialName = req.getParameter("materialName");

        // 按创建时间倒序排序
        queryWrapper.orderByDesc("create_time");

        // 创建分页对象
        Page<WmsPurchaseOrder> page = new Page<>(pageNo, pageSize);
        IPage<WmsPurchaseOrder> pageList;

        // 根据是否有物料查询条件决定查询方式
        if (materialCode != null && !materialCode.isEmpty() || materialName != null && !materialName.isEmpty()) {
            // 如果有物料查询条件，需要关联明细表查询
            Map<String, Object> params = new HashMap<>();
            params.put("materialCode", materialCode);
            params.put("materialName", materialName);

            // 将QueryWrapper中的条件转换为Map
            for (String key : parameterMap.keySet()) {
                if (parameterMap.get(key) != null && parameterMap.get(key).length > 0) {
                    params.put(key, parameterMap.get(key)[0]);
                }
            }

            // 调用服务层方法进行查询
            pageList = wmsPurchaseOrderService.queryPurchaseOrderPageList(page, params);
        } else {
            // 普通查询
            pageList = wmsPurchaseOrderService.page(page, queryWrapper);
        }

        // 给pageList中的WmsPurchaseOrder添加审核人员信息
        pageList.getRecords().forEach(purchaseOrder -> {
            if (purchaseOrder.getApproveBy() != null) {
                SysEmployee employee = employeeService.getEmployeeByUsername(purchaseOrder.getApproveBy());
                if (employee != null) {
                    purchaseOrder.setApproveName(employee.getEmpName());
                }
            }
        });

        return Result.OK(pageList);
    }

    /**
     * 根据ID查询采购单详情
     *
     * @param id
     * @return
     */
    @AutoLog(value = "采购单-详情")
    @ApiOperation(value = "采购单-详情", notes = "采购单-详情")
    @GetMapping(value = "/queryById")
    public Result<WmsPurchaseOrderVO> queryById(@RequestParam(name = "id") String id) {
        WmsPurchaseOrderVO wmsPurchaseOrderVO = wmsPurchaseOrderService.getPurchaseOrderById(id);
        if (wmsPurchaseOrderVO.getApproveBy() != null) {
            SysEmployee employee = employeeService.getEmployeeByUsername(wmsPurchaseOrderVO.getApproveBy());
            if (employee != null) {
                wmsPurchaseOrderVO.setApproveName(employee.getEmpName());
            }
        }
        if (wmsPurchaseOrderVO == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmsPurchaseOrderVO);
    }

    /**
     * 查询采购单明细列表
     *
     * @param purchaseOrderId
     * @return
     */
    @AutoLog(value = "采购单-明细列表")
    @ApiOperation(value = "采购单-明细列表", notes = "采购单-明细列表")
    @GetMapping(value = "/detail/list")
    public Result<List<WmsPurchaseOrderDetail>> queryDetailList(@RequestParam(name = "purchaseOrderId") String purchaseOrderId) {
        List<WmsPurchaseOrderDetail> detailList = wmsPurchaseOrderDetailService.queryDetailList(purchaseOrderId);
        return Result.OK(detailList);
    }

    /**
     * 新增采购单
     *
     * @param wmsPurchaseOrderVO
     * @return
     */
    @AutoLog(value = "采购单-新增")
    @ApiOperation(value = "采购单-新增", notes = "采购单-新增")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody WmsPurchaseOrderVO wmsPurchaseOrderVO) {
        return wmsPurchaseOrderService.saveOrder(wmsPurchaseOrderVO);
    }

    /**
     * 编辑采购单
     *
     * @param wmsPurchaseOrderVO
     * @return
     */
    @AutoLog(value = "采购单-编辑")
    @ApiOperation(value = "采购单-编辑", notes = "采购单-编辑")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody WmsPurchaseOrderVO wmsPurchaseOrderVO) {
        return wmsPurchaseOrderService.updateOrder(wmsPurchaseOrderVO);
    }

    /**
     * 删除采购单
     *
     * @param id
     * @return
     */
    @AutoLog(value = "采购单-删除")
    @ApiOperation(value = "采购单-删除", notes = "采购单-删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        return wmsPurchaseOrderService.deleteOrder(id);
    }

    /**
     * 批量删除采购单
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "采购单-批量删除")
    @ApiOperation(value = "采购单-批量删除", notes = "采购单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        return wmsPurchaseOrderService.deleteOrders(idList);
    }

    /**
     * 提交采购单审批
     *
     * @param id
     * @return
     */
    @AutoLog(value = "采购单-提交审批")
    @ApiOperation(value = "采购单-提交审批", notes = "采购单-提交审批")
    @PostMapping(value = "/submit")
    public Result<?> submit(@RequestParam(name = "id") String id) {
        return wmsPurchaseOrderService.submitOrder(id);
    }

    /**
     * 审批采购单
     *
     * @param params 包含id和approveResult
     * @return
     */
    @AutoLog(value = "采购单-审批")
    @ApiOperation(value = "采购单-审批", notes = "采购单-审批")
    @PostMapping(value = "/approve")
    public Result<?> approve(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        String id = (String) params.get("id");
        Integer approveResult = Integer.valueOf(params.get("approveResult").toString());
        String approveRemark = (String) params.get("approveRemark");


        // 获取当前登录用户
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = user.getUsername();
        params.put("approveBy", username);
        params.put("approveTime", new Date());

        return wmsPurchaseOrderService.approveOrder(id, approveResult, approveRemark, params);
    }

    /**
     * 取消采购单
     *
     * @param id
     * @return
     */
    @AutoLog(value = "采购单-取消")
    @ApiOperation(value = "采购单-取消", notes = "采购单-取消")
    @PostMapping(value = "/cancel")
    public Result<?> cancel(@RequestParam(name = "id") String id) {
        return wmsPurchaseOrderService.cancelOrder(id);
    }

    /**
     * 导出采购单
     *
     * @param wmsPurchaseOrder
     * @param request
     * @return
     */
    @AutoLog(value = "采购单-导出")
    @ApiOperation(value = "采购单-导出", notes = "采购单-导出")
    @GetMapping(value = "/exportXls")
    public ModelAndView exportXls(WmsPurchaseOrder wmsPurchaseOrder, HttpServletRequest request) {
        return super.exportXls(request, wmsPurchaseOrder, WmsPurchaseOrder.class, "采购单");
    }

    /**
     * 获取已审核未执行完成且未生成有效入库单的采购单列表
     *
     * @return
     */
    @AutoLog(value = "采购单-获取已审核未执行完成且未生成有效入库单的采购单列表")
    @ApiOperation(value = "采购单-获取已审核未执行完成且未生成有效入库单的采购单列表", notes = "采购单-获取已审核未执行完成且未生成有效入库单的采购单列表")
    @GetMapping(value = "/getApprovedUncompletedList")
    public Result<List<WmsPurchaseOrder>> getApprovedUncompletedList() {
        // 使用QueryWrapper排除已经生成有效入库单的采购单
        QueryWrapper<WmsPurchaseOrder> queryWrapper = new QueryWrapper<>();

        // 状态为7、8
        queryWrapper.in("status", 7, 8);
        queryWrapper.eq("is_completed", 0);

        // 按创建时间降序排序
        queryWrapper.orderByDesc("create_time");

        List<WmsPurchaseOrder> orderList = wmsPurchaseOrderService.list(queryWrapper);

        // 添加审核人员信息
        orderList.forEach(purchaseOrder -> {
            if (purchaseOrder.getApproveBy() != null) {
                SysEmployee employee = employeeService.getEmployeeByUsername(purchaseOrder.getApproveBy());
                if (employee != null) {
                    purchaseOrder.setApproveName(employee.getEmpName());
                }
            }
        });

        log.info("获取已审核未执行完成且未生成有效入库单的采购单数量: {}", orderList.size());
        return Result.OK(orderList);
    }

    /**
     * 根据采购单号查询采购单详情和明细
     *
     * @param orderNo 采购单号
     * @return
     */
    @AutoLog(value = "采购单-根据采购单号查询详情和明细")
    @ApiOperation(value = "采购单-根据采购单号查询详情和明细", notes = "采购单-根据采购单号查询详情和明细")
    @GetMapping(value = "/queryDetailByOrderNo")
    public Result<?> queryDetailByOrderNo(@RequestParam(name = "orderNo") String orderNo) {
        // 先查询采购单主表信息
        QueryWrapper<WmsPurchaseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("purchase_no", orderNo);
        WmsPurchaseOrder purchaseOrder = wmsPurchaseOrderService.getOne(queryWrapper);

        if (purchaseOrder == null) {
            return Result.error("未找到采购单信息");
        }

        // 查询采购单明细
        List<WmsPurchaseOrderDetail> detailList = wmsPurchaseOrderDetailService.queryDetailList(purchaseOrder.getId());

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("purchaseOrder", purchaseOrder);
        result.put("detailList", detailList);

        // 添加审核人员信息
        if (purchaseOrder.getApproveBy() != null) {
            SysEmployee employee = employeeService.getEmployeeByUsername(purchaseOrder.getApproveBy());
            if (employee != null) {
                purchaseOrder.setApproveName(employee.getEmpName());
            }
        }

        return Result.OK(result);
    }

    @Autowired
    private IWmsInboundOrderService inboundOrderService;

    /**
     * 保存采购到货信息
     *
     * @param arrivalData 包含采购单ID、到货日期和明细信息
     * @return
     */
    @AutoLog(value = "采购单-保存到货信息")
    @ApiOperation(value = "采购单-保存到货信息", notes = "采购单-保存到货信息")
    @PostMapping(value = "/saveArrival")
    public Result<?> saveArrival(@RequestBody Map<String, Object> arrivalData) {
        String purchaseOrderId = (String) arrivalData.get("purchaseOrderId");
        String arrivalDate = (String) arrivalData.get("arrivalDate");
        List<Map<String, Object>> details = (List<Map<String, Object>>) arrivalData.get("details");
        List<Map<String, Object>> unqualifiedList = (List<Map<String, Object>>) arrivalData.get("unqualifiedList");

        if (purchaseOrderId == null || arrivalDate == null || details == null || details.isEmpty()) {
            return Result.error("参数错误");
        }

        // 获取当前登录用户
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = user.getUsername();

        try {
            // 调用服务层方法保存到货信息
            Result<?> result = wmsPurchaseOrderService.saveArrivalInfo(purchaseOrderId, arrivalDate, details, unqualifiedList, username);

            if (result.isSuccess()) {
                // 到货信息保存成功后，自动生成采购入库单
                try {
                    String inboundOrderId = inboundOrderService.autoGenerateInboundOrderFromArrival(
                            purchaseOrderId, arrivalDate, details, username);

                    if (StringUtils.isNotBlank(inboundOrderId)) {
                        log.info("采购单[{}]到货后自动生成入库单成功，入库单ID: {}", purchaseOrderId, inboundOrderId);
                        // 在返回结果中添加生成的入库单ID信息
                        Map<String, Object> resultData = new HashMap<>();
                        resultData.put("message", "到货信息保存成功，已自动生成采购入库单");
                        resultData.put("inboundOrderId", inboundOrderId);
                        return Result.OK(resultData);
                    } else {
                        log.info("采购单[{}]没有合格物料，未生成入库单", purchaseOrderId);
                        return Result.OK("到货信息保存成功，但没有合格物料可入库");
                    }
                } catch (Exception e) {
                    log.error("自动生成采购入库单失败，采购单ID: {}", purchaseOrderId, e);
                    // 入库单生成失败不影响到货信息保存，只记录日志并提示用户
                    return Result.OK("到货信息保存成功，但自动生成入库单失败: " + e.getMessage());
                }
            }

            return result;
        } catch (Exception e) {
            log.error("保存采购到货信息失败", e);
            return Result.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 获取采购质检明细数据
     *
     * @param purchaseOrderId 采购单ID
     * @return 质检明细列表
     */
    @AutoLog(value = "采购单-获取质检明细")
    @ApiOperation(value = "采购单-获取质检明细", notes = "采购单-获取质检明细")
    @GetMapping(value = "/getInspectionList")
    public Result<?> getInspectionList(@RequestParam(name = "purchaseOrderId") String purchaseOrderId) {
        if (StringUtils.isBlank(purchaseOrderId)) {
            return Result.error("采购单ID不能为空");
        }

        try {
            // 查询采购质检明细数据
            List<WmsPurchaseArrivalInspection> inspectionList = wmsPurchaseArrivalInspectionService.list(
                    new QueryWrapper<WmsPurchaseArrivalInspection>()
                            .eq("purchase_order_id", purchaseOrderId)
                            .orderByAsc("inspection_result") // 先显示合格的，再显示不合格的
                            .orderByAsc("material_code")
            );

            return Result.OK(inspectionList);
        } catch (Exception e) {
            log.error("获取采购质检明细失败", e);
            return Result.error("获取质检明细失败: " + e.getMessage());
        }
    }

    /**
     * 获取退货/换货记录列表
     *
     * @param purchaseOrderId 采购单ID
     * @return 退货/换货记录列表
     */
    @GetMapping("/returnExchange/list")
    @ApiOperation(value = "获取退货/换货记录列表", notes = "根据采购单ID获取退货/换货记录列表")
    public Result<?> getReturnExchangeList(@RequestParam String purchaseOrderId) {
        try {
            List<WmsPurchaseReturnExchange> list = wmsPurchaseReturnExchangeService.getByPurchaseOrderId(purchaseOrderId);
            return Result.ok(list);
        } catch (Exception e) {
            log.error("获取退货/换货记录列表失败", e);
            return Result.error("获取退货/换货记录列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据质检记录ID获取退货/换货记录
     *
     * @param inspectionId 质检记录ID
     * @return 退货/换货记录列表
     */
    @GetMapping("/returnExchange/listByInspection")
    @ApiOperation(value = "根据质检记录ID获取退货/换货记录", notes = "根据质检记录ID获取退货/换货记录")
    public Result<?> getReturnExchangeListByInspection(@RequestParam String inspectionId) {
        try {
            List<WmsPurchaseReturnExchange> list = wmsPurchaseReturnExchangeService.getByInspectionId(inspectionId);
            return Result.ok(list);
        } catch (Exception e) {
            log.error("获取退货/换货记录失败", e);
            return Result.error("获取退货/换货记录失败: " + e.getMessage());
        }
    }

    /**
     * 创建退货记录
     *
     * @param params 退货参数
     * @return 操作结果
     */
    @PostMapping("/returnExchange/createReturn")
    @ApiOperation(value = "创建退货记录", notes = "创建退货记录")
    public Result<?> createReturnRecord(@RequestBody Map<String, Object> params) {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = user.getUsername();
            return wmsPurchaseReturnExchangeService.createReturnRecord(params, username);
        } catch (Exception e) {
            log.error("创建退货记录失败", e);
            return Result.error("创建退货记录失败: " + e.getMessage());
        }
    }

    /**
     * 创建换货记录
     *
     * @param params 换货参数
     * @return 操作结果
     */
    @PostMapping("/returnExchange/createExchange")
    @ApiOperation(value = "创建换货记录", notes = "创建换货记录")
    public Result<?> createExchangeRecord(@RequestBody Map<String, Object> params) {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = user.getUsername();
            return wmsPurchaseReturnExchangeService.createExchangeRecord(params, username);
        } catch (Exception e) {
            log.error("创建换货记录失败", e);
            return Result.error("创建换货记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取采购单物料已到货数量
     *
     * @param purchaseOrderId 采购单ID
     * @return 物料已到货数量 {materialId: receivedQuantity, ...}
     */
    @AutoLog(value = "采购单-获取物料已到货数量")
    @ApiOperation(value = "采购单-获取物料已到货数量", notes = "采购单-获取物料已到货数量")
    @GetMapping(value = "/arrival/materialQuantity")
    public Result<?> getMaterialArrivalQuantity(@RequestParam(name = "purchaseOrderId") String purchaseOrderId) {
        if (StringUtils.isBlank(purchaseOrderId)) {
            return Result.error("采购单ID不能为空");
        }

        try {
            // 查询采购单明细
            List<WmsPurchaseOrderDetail> detailList = wmsPurchaseOrderDetailService.list(
                    new QueryWrapper<WmsPurchaseOrderDetail>()
                            .eq("purchase_order_id", purchaseOrderId)
            );

            if (detailList == null || detailList.isEmpty()) {
                return Result.OK(new HashMap<>());
            }

            // 查询采购质检记录 - 统计所有到货记录（包括合格和不合格）
            List<WmsPurchaseArrivalInspection> inspectionList = wmsPurchaseArrivalInspectionService.list(
                    new QueryWrapper<WmsPurchaseArrivalInspection>()
                            .eq("purchase_order_id", purchaseOrderId)
                            .select("material_id", "arrival_quantity")
            );

            // 统计每个物料的已到货数量（包括合格和不合格）
            Map<String, Double> materialQuantityMap = new HashMap<>();

            for (WmsPurchaseArrivalInspection inspection : inspectionList) {
                String materialId = inspection.getMaterialId();
                Double arrivalQuantity = inspection.getArrivalQuantity() != null ?
                        inspection.getArrivalQuantity().doubleValue() : 0.0;

                // 累加同一物料的到货数量
                materialQuantityMap.put(materialId,
                        materialQuantityMap.getOrDefault(materialId, 0.0) + arrivalQuantity);
            }

            // 打印日志，帮助调试
            log.info("采购单ID: {}, 已到货数量统计: {}", purchaseOrderId, materialQuantityMap);

            return Result.OK(materialQuantityMap);
        } catch (Exception e) {
            log.error("获取物料已到货数量失败", e);
            return Result.error("获取物料已到货数量失败: " + e.getMessage());
        }
    }

    /**
     * 获取采购到货历史记录
     *
     * @param purchaseOrderId 采购单ID
     * @return 到货历史记录列表
     */
    @AutoLog(value = "采购单-获取到货历史记录")
    @ApiOperation(value = "采购单-获取到货历史记录", notes = "采购单-获取到货历史记录")
    @GetMapping(value = "/arrival/history")
    public Result<?> getArrivalHistory(@RequestParam(name = "purchaseOrderId") String purchaseOrderId) {
        if (StringUtils.isBlank(purchaseOrderId)) {
            return Result.error("采购单ID不能为空");
        }

        try {
            // 查询该采购单所有的到货记录，按到货日期分组
            List<Map<String, Object>> arrivalHistoryList = wmsPurchaseArrivalInspectionService.getArrivalHistoryByPurchaseOrderId(purchaseOrderId);

            return Result.OK(arrivalHistoryList);
        } catch (Exception e) {
            log.error("获取到货历史记录失败", e);
            return Result.error("获取到货历史记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取合格且未处理的质检记录
     *
     * @param purchaseOrderNo 采购单号
     * @return 合格且未处理的质检记录列表
     */
    @AutoLog(value = "采购单-获取合格且未处理的质检记录")
    @ApiOperation(value = "采购单-获取合格且未处理的质检记录", notes = "采购单-获取合格且未处理的质检记录")
    @GetMapping(value = "/inspection/getQualifiedUnprocessed")
    public Result<?> getQualifiedUnprocessedInspection(@RequestParam(name = "purchaseOrderNo") String purchaseOrderNo) {
        if (StringUtils.isBlank(purchaseOrderNo)) {
            return Result.error("采购单号不能为空");
        }

        try {
            // 查询采购单信息，获取采购单ID
            WmsPurchaseOrder purchaseOrder = wmsPurchaseOrderService.getOne(
                    new QueryWrapper<WmsPurchaseOrder>()
                            .eq("purchase_no", purchaseOrderNo).eq("is_completed", 0)
            );

            if (purchaseOrder == null) {
                return Result.error("未找到采购单信息");
            }

            // 查询采购单明细，获取原始采购数量
            List<WmsPurchaseOrderDetail> detailList = wmsPurchaseOrderDetailService.list(
                    new QueryWrapper<WmsPurchaseOrderDetail>()
                            .eq("purchase_order_id", purchaseOrder.getId())
            );

            // 构建物料ID与原始采购数量的映射
            Map<String, BigDecimal> originalQuantityMap = new HashMap<>();
            //构建物料ID与单价的映射
            Map<String, BigDecimal> unitPriceMap = new HashMap<>();
            for (WmsPurchaseOrderDetail detail : detailList) {
                originalQuantityMap.put(detail.getMaterialId(), detail.getQuantity());
                unitPriceMap.put(detail.getMaterialId(), detail.getUnitPrice());
            }

            // 查询合格且未处理的质检记录
            List<WmsPurchaseArrivalInspection> inspectionList = wmsPurchaseArrivalInspectionService.list(
                    new QueryWrapper<WmsPurchaseArrivalInspection>()
                            .eq("purchase_order_no", purchaseOrderNo)
                            .eq("inspection_result", 1) // 合格
                            .eq("status", 0) // 未处理
            );

            // 为每条质检记录添加原始采购数量信息
            for (WmsPurchaseArrivalInspection inspection : inspectionList) {
                BigDecimal originalQuantity = originalQuantityMap.get(inspection.getMaterialId());
                BigDecimal unitCost = unitPriceMap.get(inspection.getMaterialId());
                if (originalQuantity != null) {
                    inspection.setOriginalQuantity(originalQuantity);
                }
                if (unitCost != null) {
                    inspection.setUnitCost(unitCost);
                }
            }

            //根据物料ID，对质检记录进行数量汇总 YC5501D有两条质检信息  合并为一条，质检合格数量汇总
            Map<String, WmsPurchaseArrivalInspection> mergedInspectionMap = new HashMap<>();
            // 保存每个物料ID对应的所有原始记录ID
            Map<String, List<String>> materialIdToInspectionIds = new HashMap<>();

            for (WmsPurchaseArrivalInspection inspection : inspectionList) {
                String materialId = inspection.getMaterialId();

                // 保存原始记录ID
                if (!materialIdToInspectionIds.containsKey(materialId)) {
                    materialIdToInspectionIds.put(materialId, new ArrayList<>());
                }
                materialIdToInspectionIds.get(materialId).add(inspection.getId());

                if (mergedInspectionMap.containsKey(materialId)) {
                    // 如果已存在相同物料ID的记录，则合并数量
                    WmsPurchaseArrivalInspection existingInspection = mergedInspectionMap.get(materialId);

                    // 合并合格数量
                    BigDecimal mergedQualifiedQuantity = existingInspection.getQualifiedQuantity().add(
                            inspection.getQualifiedQuantity() != null ? inspection.getQualifiedQuantity() : BigDecimal.ZERO
                    );
                    existingInspection.setQualifiedQuantity(mergedQualifiedQuantity);

                    // 合并到货数量
                    BigDecimal mergedArrivalQuantity = existingInspection.getArrivalQuantity().add(
                            inspection.getArrivalQuantity() != null ? inspection.getArrivalQuantity() : BigDecimal.ZERO
                    );
                    existingInspection.setArrivalQuantity(mergedArrivalQuantity);

                    // 合并不合格数量
                    BigDecimal mergedUnqualifiedQuantity = existingInspection.getUnqualifiedQuantity().add(
                            inspection.getUnqualifiedQuantity() != null ? inspection.getUnqualifiedQuantity() : BigDecimal.ZERO
                    );
                    existingInspection.setUnqualifiedQuantity(mergedUnqualifiedQuantity);

                } else {
                    // 如果不存在相同物料ID的记录，则添加到Map中
                    mergedInspectionMap.put(materialId, inspection);
                }
            }

            // 将合并后的记录转换为List
            List<WmsPurchaseArrivalInspection> mergedInspectionList = new ArrayList<>(mergedInspectionMap.values());

            // 为每个合并后的记录添加原始记录ID列表
            for (WmsPurchaseArrivalInspection mergedInspection : mergedInspectionList) {
                String materialId = mergedInspection.getMaterialId();
                List<String> originalIds = materialIdToInspectionIds.get(materialId);
                if (originalIds != null && !originalIds.isEmpty()) {
                    // 使用逗号分隔的字符串保存所有原始记录ID
                    mergedInspection.setRemark(String.join(",", originalIds));
                }
            }

            // 打印日志，帮助调试
            log.info("采购单号: {}, 合格且未处理的质检记录数量(合并前): {}, 合并后: {}",
                    purchaseOrderNo, inspectionList.size(), mergedInspectionList.size());

            return Result.OK(mergedInspectionList);
        } catch (Exception e) {
            log.error("获取合格且未处理的质检记录失败", e);
            return Result.error("获取合格且未处理的质检记录失败: " + e.getMessage());
        }
    }

    /**
     * 更新质检记录状态
     *
     * @param params 包含ids的参数对象
     * @return 操作结果
     */
    @AutoLog(value = "采购单-更新质检记录状态")
    @ApiOperation(value = "采购单-更新质检记录状态", notes = "采购单-更新质检记录状态")
    @PostMapping(value = "/inspection/updateStatus")
    public Result<?> updateInspectionStatus(@RequestBody Map<String, Object> params) {
        String ids = (String) params.get("ids");
        if (StringUtils.isBlank(ids)) {
            return Result.error("质检记录ID不能为空");
        }

        try {
            // 将逗号分隔的ID转换为列表
            List<String> idList = Arrays.asList(ids.split(","));

            // 打印日志，帮助调试
            log.info("更新质检记录状态，ID列表: {}", idList);

            // 获取质检记录详情，用于后续更新采购单状态
            List<WmsPurchaseArrivalInspection> inspectionList = wmsPurchaseArrivalInspectionService.listByIds(idList);
            if (inspectionList == null || inspectionList.isEmpty()) {
                return Result.error("未找到对应的质检记录");
            }

            // 提取所有涉及的采购单号
            Set<String> purchaseOrderNos = inspectionList.stream()
                    .map(WmsPurchaseArrivalInspection::getPurchaseOrderNo)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toSet());

            // 更新质检记录状态为已处理
            boolean success = wmsPurchaseArrivalInspectionService.lambdaUpdate()
                    .in(WmsPurchaseArrivalInspection::getId, idList)
                    .set(WmsPurchaseArrivalInspection::getStatus, 1) // 已处理
                    .update();

            if (success) {
                log.info("质检记录状态更新成功");

                // 对每个涉及的采购单，检查是否所有质检记录都已处理
                for (String purchaseOrderNo : purchaseOrderNos) {
                    // 查询采购单信息
                    WmsPurchaseOrder purchaseOrder = wmsPurchaseOrderService.getOne(
                            new QueryWrapper<WmsPurchaseOrder>()
                                    .eq("purchase_no", purchaseOrderNo).eq("is_completed", 0)
                    );

                    if (purchaseOrder != null) {
                        // 查询该采购单下是否还有未处理的合格质检记录
                        Long unprocessedCount = wmsPurchaseArrivalInspectionService.count(
                                new QueryWrapper<WmsPurchaseArrivalInspection>()
                                        .eq("purchase_order_no", purchaseOrderNo)
                                        .eq("inspection_result", 1)
                                        .eq("status", 0) // 未处理
                        );

                        // 如果没有未处理的质检记录，且采购单状态为已到货，则更新采购单为已完成
                        if (unprocessedCount == 0 && (purchaseOrder.getStatus() == 7)) { // 7表示已到货状态
                            wmsPurchaseOrderService.lambdaUpdate()
                                    .eq(WmsPurchaseOrder::getId, purchaseOrder.getId())
                                    .set(WmsPurchaseOrder::getIsCompleted, 1) // 设置为已完成
                                    .update();

                            log.info("采购单 {} 所有质检记录已处理，已更新为已完成状态", purchaseOrderNo);
                        }
                    }
                }

                return Result.OK("更新成功");
            } else {
                log.warn("质检记录状态更新失败");
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新质检记录状态失败", e);
            return Result.error("更新质检记录状态失败: " + e.getMessage());
        }
    }

    /**
     * 处理退货/换货记录
     *
     * @param params 处理参数
     * @return 操作结果
     */
    @PostMapping("/returnExchange/process")
    @ApiOperation(value = "处理退货/换货记录", notes = "处理退货/换货记录")
    public Result<?> processReturnExchangeRecord(@RequestBody Map<String, Object> params) {
        try {
            String id = (String) params.get("id");
            Integer status = (Integer) params.get("status");
            String remark = (String) params.get("remark");
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = user.getUsername();

            return wmsPurchaseReturnExchangeService.processRecord(id, status, remark, username);
        } catch (Exception e) {
            log.error("处理退货/换货记录失败", e);
            return Result.error("处理退货/换货记录失败: " + e.getMessage());
        }
    }

    /**
     * 取消退货/换货记录
     *
     * @param params 取消参数
     * @return 操作结果
     */
    @PostMapping("/returnExchange/cancel")
    @ApiOperation(value = "取消退货/换货记录", notes = "取消退货/换货记录")
    public Result<?> cancelReturnExchangeRecord(@RequestBody Map<String, Object> params) {
        try {
            String id = (String) params.get("id");
            String remark = (String) params.get("remark");
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = user.getUsername();

            return wmsPurchaseReturnExchangeService.cancelRecord(id, remark, username);
        } catch (Exception e) {
            log.error("取消退货/换货记录失败", e);
            return Result.error("取消退货/换货记录失败: " + e.getMessage());
        }
    }

    /**
     * 批量创建退货记录
     *
     * @param params 批量退货参数
     * @return 操作结果
     */
    @PostMapping("/returnExchange/batchCreateReturn")
    @ApiOperation(value = "批量创建退货记录", notes = "批量创建退货记录")
    public Result<?> batchCreateReturnRecord(@RequestBody Map<String, Object> params) {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = user.getUsername();
            return wmsPurchaseReturnExchangeService.batchCreateReturnRecord(params, username);
        } catch (Exception e) {
            log.error("批量创建退货记录失败", e);
            return Result.error("批量创建退货记录失败: " + e.getMessage());
        }
    }

    /**
     * 批量创建换货记录
     *
     * @param params 批量换货参数
     * @return 操作结果
     */
    @PostMapping("/returnExchange/batchCreateExchange")
    @ApiOperation(value = "批量创建换货记录", notes = "批量创建换货记录")
    public Result<?> batchCreateExchangeRecord(@RequestBody Map<String, Object> params) {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String username = user.getUsername();
            return wmsPurchaseReturnExchangeService.batchCreateExchangeRecord(params, username);
        } catch (Exception e) {
            log.error("批量创建换货记录失败", e);
            return Result.error("批量创建换货记录失败: " + e.getMessage());
        }
    }

    /**
     * 从分配方案生成采购单
     */
    @AutoLog(value = "采购单管理-从分配方案生成采购单")
    @ApiOperation(value = "采购单管理-从分配方案生成采购单", notes = "根据未分配物料生成采购单")
    @PostMapping(value = "/generateFromAllocation")
    public Result<?> generateFromAllocation(@RequestBody Map<String, Object> params) {
        try {
            log.info("开始从分配方案生成采购单，参数: {}", params);

            // 获取当前登录用户
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String operator = sysUser != null ? sysUser.getUsername() : "system";

            // 获取物料列表
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> materialList = (List<Map<String, Object>>) params.get("materialList");
            if (materialList == null || materialList.isEmpty()) {
                return Result.error("物料列表不能为空");
            }

            // 构建采购单VO对象
            WmsPurchaseOrderVO purchaseOrderVO = new WmsPurchaseOrderVO();

            // 生成采购单号
            String timestamp = String.valueOf(System.currentTimeMillis());
            String purchaseNo = "PO" + timestamp.substring(timestamp.length() - 10);

            purchaseOrderVO.setPurchaseNo(purchaseNo);
            purchaseOrderVO.setSupplier("待确定供应商");
            purchaseOrderVO.setStatus(1); // 草稿状态
            purchaseOrderVO.setIsAutoGenerated(1); // 自动生成
            purchaseOrderVO.setCreateBy(operator);
            purchaseOrderVO.setCreateTime(new Date());
            purchaseOrderVO.setRemark("由分配方案自动生成");

            // 构建采购明细列表
            List<WmsPurchaseOrderDetailVO> detailList = new ArrayList<>();
            BigDecimal totalAmount = BigDecimal.ZERO;

            for (Map<String, Object> material : materialList) {
                WmsPurchaseOrderDetailVO detail = new WmsPurchaseOrderDetailVO();

                detail.setMaterialId(getString(material, "materialId"));
                detail.setMaterialCode(getString(material, "materialCode"));
                detail.setMaterialName(getString(material, "materialName"));
                detail.setMaterialType(getInteger(material, "materialType"));
                detail.setSpecification(getString(material, "specification"));
                detail.setUnit(getString(material, "unit"));
                detail.setQuantity(getBigDecimal(material, "planQuantity"));
                detail.setUnitPrice(getBigDecimal(material, "unitCost"));

                // 计算金额
                BigDecimal amount = detail.getQuantity().multiply(detail.getUnitPrice());
                detail.setAmount(amount);
                totalAmount = totalAmount.add(amount);

                detail.setReceivedQuantity(BigDecimal.ZERO);
                detail.setRemark("由分配方案自动生成");

                detailList.add(detail);
            }

            purchaseOrderVO.setDetailList(detailList);
            purchaseOrderVO.setTotalAmount(totalAmount);

            // 调用服务层方法保存采购单
            Result<?> result = wmsPurchaseOrderService.saveOrder(purchaseOrderVO);

            if (result.isSuccess()) {
                Map<String, Object> resultData = new HashMap<>();
                resultData.put("purchaseOrderId", purchaseOrderVO.getId());
                resultData.put("purchaseNo", purchaseNo);
                resultData.put("totalAmount", totalAmount);
                return Result.OK("采购单生成成功", resultData);
            } else {
                return result;
            }

        } catch (Exception e) {
            log.error("从分配方案生成采购单失败", e);
            return Result.error("生成采购单失败: " + e.getMessage());
        }
    }

    /**
     * 辅助方法：从Map中获取String值
     */
    private String getString(Map<String, Object> map, String key) {
        Object value = map.get(key);
        return value != null ? value.toString() : null;
    }

    /**
     * 辅助方法：从Map中获取Integer值
     */
    private Integer getInteger(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        if (value instanceof Integer) {
            return (Integer) value;
        }
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        if (value instanceof String) {
            try {
                return Integer.parseInt((String) value);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 自动生成采购单
     *
     * @param params
     * @return
     */
    @AutoLog(value = "采购单-自动生成")
    @ApiOperation(value = "采购单-自动生成", notes = "采购单-自动生成")
    @PostMapping(value = "/generateFromWarnings")
    public Result<?> autoGeneratePurchaseOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String supplier = (String) params.get("supplier");
            String expectedArrivalDate = (String) params.get("expectedArrivalDate");
            String remark = (String) params.get("remarks");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> purchaseDetails = (List<Map<String, Object>>) params.get("purchaseDetails");

            if (StringUtils.isBlank(supplier)) {
                return Result.error("请输入供应商");
            }

            if (purchaseDetails == null || purchaseDetails.isEmpty()) {
                return Result.error("请添加采购明细");
            }

            // 解析预警ID列表
            String warningIdsStr = (String) params.get("warningIds");
            List<String> warningIds = Arrays.asList(warningIdsStr.split(","));
            
            // 调用服务层方法生成采购单
            Result<?> result = wmsPurchaseOrderService.generatePurchaseOrderFromWarnings(warningIds, supplier);

            return result;

        } catch (Exception e) {
            log.error("自动生成采购单失败", e);
            return Result.error("生成采购单失败: " + e.getMessage());
        }
    }

    /**
     * 辅助方法：从Map中获取BigDecimal值
     */
    private BigDecimal getBigDecimal(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return BigDecimal.ZERO;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Number) {
            return BigDecimal.valueOf(((Number) value).doubleValue());
        }
        if (value instanceof String) {
            try {
                return new BigDecimal((String) value);
            } catch (NumberFormatException e) {
                return BigDecimal.ZERO;
            }
        }
        return BigDecimal.ZERO;
    }

}